package com.wanfajie.smsdistribute.receiver.sms

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.telephony.SmsManager
import android.util.Log
import com.j256.ormlite.dao.Dao
import com.wanfajie.smsdistribute.db.bean.sms.SmsBean
import com.wanfajie.smsdistribute.db.bean.sms.SmsPartBean
import com.wanfajie.smsdistribute.db.helper.SmsDatabaseHelper
import com.wanfajie.smsdistribute.db.quietInvoke
import java.sql.SQLException

class SmsSentStatusReceiver: BroadcastReceiver() {

    companion object {

        private const val TAG = "SmsSentStatusReceiver"
        private const val SENT_SMS_ACTION = "com.wanfajie.smsdistribute.ACTION.SENT_SMS_ACTION"
        private const val DELIVERY_SMS_ACTION = "com.wanfajie.smsdistribute.ACTION.DELIVERY_SMS_ACTION"
        private const val EXTRA_SMS_ID = "sms_id"

        private fun getSmsManager(subId: Int): SmsManager {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                SmsManager.getSmsManagerForSubscriptionId(subId)
            } else {
                SmsManager.getDefault()
            }
        }

        fun sendSmsMessage(ctx: Context, sendTo: String, message: String,
                                   subId: Int): SmsBean {

            val smsManager = getSmsManager(subId)
            val dividedMessage = smsManager.divideMessage(message)

            val dao = SmsDatabaseHelper(ctx).getDao(SmsBean::class.java)
            val bean = SmsBean(sendTo = sendTo,
                    message = message,
                    subIndex = subId,
                    partCount = dividedMessage.size)

            quietInvoke(TAG, false, SQLException::class) {
                dao.create(bean) > 0
            }

            val smsId = bean.id

            val piArray = ArrayList<PendingIntent>(dividedMessage.size)

            for (it in dividedMessage) {
                val newIntent = Intent(SENT_SMS_ACTION)
                newIntent.putExtra(EXTRA_SMS_ID, smsId)
                newIntent.flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES

                val pi = PendingIntent.getBroadcast(ctx, smsId, newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
                piArray.add(pi)
            }

            smsManager.sendMultipartTextMessage(sendTo, null, dividedMessage, piArray, null)
            return bean
        }

        fun sendSmsMessage(ctx: Context, sms: SmsBean) {

            val smsManager = getSmsManager(sms.subIndex)
            val dividedMessage = smsManager.divideMessage(sms.message)
            val smsId = sms.id

            val piArray = ArrayList<PendingIntent>(dividedMessage.size)

            for (it in dividedMessage) {
                val newIntent = Intent(SENT_SMS_ACTION)
                newIntent.putExtra(EXTRA_SMS_ID, smsId)
                newIntent.flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES

                val pi = PendingIntent.getBroadcast(ctx, smsId, newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
                piArray.add(pi)
            }

            smsManager.sendMultipartTextMessage(sms.sendTo, null, dividedMessage, piArray, null)
        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action != SENT_SMS_ACTION)
            return

        val smsId = intent.getIntExtra(EXTRA_SMS_ID, -1)
        Log.d(TAG, "SMS_ID: $smsId, resultCode: $resultCode, Extra: ${intent.extras}")

        if (smsId == -1) {
            Log.e(TAG, "无SMS_PART_ID: ${intent.extras}")
            return
        }

        val dbHelper = SmsDatabaseHelper(context!!)
        val smsDao: Dao<SmsBean, Int> = dbHelper.getDao(SmsBean::class.java)
        val partDao: Dao<SmsPartBean, Int> = dbHelper.getDao(SmsPartBean::class.java)

        val smsBean: SmsBean = smsDao.queryForId(smsId)
        val partBean = SmsPartBean(
                sms = smsBean,
                resultCode = resultCode
        )

        partDao.create(partBean)
    }
}